import customerDetailForm from "../../customerDetail.vue";
import { utils, writeFile, readFile } from "xlsx";
import {ElMessage} from 'element-plus'
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { hasPerms } from "@/utils/auth";
import {CopyDocument} from '@element-plus/icons-vue'
import {
  customerIndex, customerLogs, getSalesList
} from "@/api/crm";
import { type Ref, reactive, ref, onMounted, h ,createVNode ,toRaw } from "vue";
import { copyTextToClipboard,getKeyList,cloneDeep, isAllEmpty,storageLocal, deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import {addDrawer, closeAllDrawer} from "@/components/ReDrawer/index";
import forms, {FormProps} from "@/views/crm/topdata/import.vue";
import {addDialog, closeDialog} from "@/components/ReDialog/index";
import { useRoute } from 'vue-router';
import { SuccessFilled, WarningFilled,Notification } from '@element-plus/icons-vue'
import {message} from "@/utils/message";
import visitForm from "@/views/crm/addVisitForm.vue";
import { importCustomerList } from "@/api/crm";
export function useOrders(tableRef: Ref) {
  const route = useRoute();
  const form = reactive({
    name: "",
    type: "1",
    search_field: "id",
    search:'',tab_id:'0',
    sortField:'top_index',
    order:'asc',
    status: null
  });

  const teamList = ref([]);
  const formRef = ref();
  const shopList = ref([]);
  const sta_order_statc = ref([]);
  const selectValue = ref([]);
  const columnsKey = ref('');
  const dataList = ref([]);
  const loading = ref(true);
  const activeStatus = ref(route.query?.order_status||'-1')
  const selectedNum = ref(0);
  const financial_status_arr = ref([]);
  const salesman_arr = ref([]);
  const shop_group_list_arr = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0, pageSize: 15,pageSizes: [10,20, 40, 60,100,200],
    currentPage: 1, background: true
  });
  const template_url = ref('');
  function onInputChange(row) {
    row.isModified = true; // 手动标记为已修改
  }
  const dataField = ref(['勾选列','展开','订单编号']);
  const db_fields_all = ref(['勾选列','展开','订单编号']);

  // Email	求和项:SA	归属人	组别	电话号码		最后期限		近期情况		最后购买时间		轮询跟进人	轮询情况

  const last_term_arr = [
    {color:'#f38080',value:'还在复购'},{color:'cyan',value:'已完复购意向'},{color:'#49af49',value:'一周'},{color:'#b1b10f',value:'等待物流'}
  ]
  const poll_arr = [
    {color:'#49af49',value:'无回复'},{color:'#b1b10f',value:'已回复（意向）'},{color:'#f38080',value:'已回复（无意向）'},{color:'cyan',value:'已完复购意向'}
    ,{color:'cyan',value:'解决售后中'},{color:'cyan',value:'已转化'}
  ]
  const tags4 = [
    {color:'#49af49',value:'已回复'},{color:'#b1b10f',value:'未回复'}
  ]

  const columns = ref([
    { label: "勾选列", type: "selection", width: 50,disabled:true,fixed:true},
    { label: "排名", prop: "top_index", width: 50,disabled:true,fixed:true,cellRenderer: ({ row, index }) => (
        <>
          {form.tab_id<3?row.top_index:row.top_type_rank}
        </>
      )},
    { label: "客户ID", prop: "id", width: 100, align: "left",disabled:true,fixed:true,sortable: "custom",cellRenderer: ({ row, index }) => (
        <>
          <el-icon onClick={() => addVisitLog(row.id)}><Notification /></el-icon>
          <el-text type="primary" size="small" data-id={row.id} onClick={seeCustomerDetail} style="padding-left:5px;">{row.id}</el-text>
          {row.isModified==true&&(hasPerms('customer:btn:allo')||hasPerms('customer:btn:genjin'))? (
            <><br/><el-button type="primary" size="small" onClick={() =>onCustomerOrder(row)} style="padding:0 10px;margin-top:-15px;">保存</el-button></>
          ) : (
            <></>
          )}
        </>
      ),},
    { label: "邮箱", prop: "email",align:'left', width: 170,fixed:true,sortable: "custom",cellRenderer: ({ row, index }) => (
      <>
        <el-icon v-copy:click={row.email}><CopyDocument /></el-icon>
        {row.email?(row.is_verified==1?<el-icon color="green"><SuccessFilled /></el-icon>:<el-icon><WarningFilled /></el-icon>):''} {row.email}</>)},

    { label: "初始SA", prop: "init_spent", sortable: "custom",width: 100,hide:form.tab_id>1},
    { label: "SA", prop: "sa", width: 100},
    { label: "总消费金额", prop: "total_spent", minWidth: 110,sortable: "custom" },
    { label: "初始归属人", prop: "own_saleman", minWidth: 100 },
    // { label: "归属人", prop: "own_saleman_id", width: 130, sortable: "custom",cellRenderer: ({ row, index }) => (
    //     <el-select size="small" v-model={row.own_saleman_id}
    //                filterable placeholder="归属人" disabled={!hasPerms('customer:btn:allo')} onChange={() =>onInputChange(row)}>
    //       <el-option key="0" label={row.own_saleman?(row.own_saleman+'不存在，请重新分配'):'请分配'} value={0} />
    //       {salesman_arr.value.map(item => {
    //         return (
    //           <el-option key={item.id} label={(item?.site_group[0]>0?(item?.sales_group):(item.dept?.name))+'-'+item.username} value={item.id} style={'background:'+item.setting.bgcolor+';color:'+item.setting.color} disabled={item.status!=1}/>
    //         );
    //       })}
    //     </el-select>
    //   )},
    { label: "电话", prop: "contact", width: 140,cellRenderer: ({ row, index }) => (
        <el-input v-model={row.contact} type="text" row="1" style="font-size: 12px; line-height: 0.75;" disabled={!hasPerms('customer:btn:allo')||(!row.isModified&&row.contact!='')} onChange={() =>onInputChange(row)} />
      )},
    { label: "UTM来源", prop: "utm_source", width: 130,cellRenderer: ({ row, index }) => (
        <el-select size="small" v-model={row.utm_source} filterable placeholder="UTM来源" disabled={!hasPerms('customer:btn:genjin')} onChange={() =>onInputChange(row)}>
          <el-option key="facebook" label="Facebook" value="facebook"/>
          <el-option key="instagram" label="Instagram" value="instagram"/>
          <el-option key="tiktok" label="Tiktok" value="tiktok"/>
          <el-option key="youtube" label="youtube" value="youtube"/>
        </el-select>
      )},

    { label: "最后发货时间", prop: "last_express_at", width: 200,cellRenderer: ({ row, index }) => (
        <el-input v-model={row.last_express_at} type="text" row="1" style="font-size: 12px; line-height: 0.75;" disabled={!hasPerms('customer:btn:genjin')} onChange={() =>onInputChange(row)} />
      )},
    { label: "最后期限", prop: "last_term", width: 130,
      cellRenderer: ({ row, index }) => (
        <el-select size="small" allow-create filterable  v-model={row.last_term} class={last_term_arr.find(x=>x.value==row.last_term)?.color?'diy':''} style={'color:#fff;background:'+last_term_arr.find(x=>x.value==row.last_term)?.color} placeholder="最后期限" disabled={!hasPerms('customer:btn:genjin')} onChange={() =>onInputChange(row)}>
          {last_term_arr.map(item => {
            return (
              <el-option key={item.value} label={item.value} value={item.value} style={'color:#fff;background:'+item.color}>{item.value}</el-option>
            );
          })}
        </el-select>
      )},
    { label: "近期情况", prop: "recent_status", width: 200,cellRenderer: ({ row, index }) => (
        <el-input v-model={row.recent_status} type="textarea" row="1" style="font-size: 12px; line-height: 0.75;" disabled={!hasPerms('customer:btn:genjin')} onChange={() =>onInputChange(row)} />
      )},
    { label: "轮询跟进人", prop: "poll_saleman_id", width: 130,sortable: "custom",cellRenderer: ({ row, index }) => (
        <el-select size="small" allow-create filterable v-model={row.poll_saleman_id}
                   placeholder="轮询跟进人" disabled={!hasPerms('customer:btn:genjin')} onChange={() =>onInputChange(row)}>
          <el-option key="0" label={row.poll_saleman_id?row.poll_saleman_id:'请分配'} value={0} />
          {salesman_arr.value.map(item => {
            return (
              <el-option key={item.id} label={(item?.site_group[0]>0?(item?.sales_group):(item.dept?.name))+'-'+item.username} value={item.id} disabled={item.status!=1}/>
            );
          })}
        </el-select>
      )},
    { label: "轮询情况", prop: "poll_remark", width: 200,cellRenderer: ({ row, index }) => (
        <el-select size="small" allow-create filterable  v-model={row.poll_remark} class={tags4.find(x=>x.value==row.poll_remark)?.color?'diy':''} style={'background:'+poll_arr.find(x=>x.value==row.poll_remark)?.color} placeholder="轮询情况" disabled={!hasPerms('customer:btn:genjin')} onChange={() =>onInputChange(row)}>
          {poll_arr.map(item => {
            return (
              <el-option key={item.value} label={item.value} value={item.value} style={item.value>0?('color:#fff;background:'+item.color):''}>{item.value}</el-option>
            );
          })}
        </el-select>
      )},

    { label: "姓名", prop: "fullname", width: 120,sortable: "custom"},
    // { label: "登录时间", prop: "login_at", width: 130,sortable: "custom"},

    { label: "国家", minWidth: 100, prop: "country.name"},
    { label: "最后回访时间", minWidth: 100, prop: "last_visit_text"},
      { label: "剩下释放时间", minWidth: 140, prop: "left_time",cellRenderer: ({ row, index }) => (
          row.left_time=='-1'? (<el-text size="small">-</el-text>) : (row.left_time>20?
            <el-text type="success" size="small" >{row.left_time}天</el-text>:
            <el-text type="danger" size="small" >{row.left_time}天</el-text>)
        )
      },
    { label: "生日", prop: "birthday", width: 100, align: "left",sortable: "custom"},
    { label: "性别", prop: "gender", width: 70},



    { label: "首次付款时间", prop: "frist_pay_at", width: 130,sortable: "custom"},
    { label: "最近访问时间", prop: "visit_at", width: 130,sortable: "custom"},
    { label: "最近订单", prop: "last_order_id", minWidth: 150,sortable: "custom"},
    { label: "总订单数", prop: "orders_count", minWidth: 90,sortable: "custom"},
    { label: "来源设备", prop: "source_device", minWidth: 110,showOverflowTooltip:true},
    { label: "utm_source", prop: "utm_source", minWidth: 110,sortable: "custom"},
    { label: "标签", prop: "tags", minWidth: 70},//
    { label: "来源域名", minWidth: 120, prop: "domain",showOverflowTooltip:true,sortable: "custom"},
    { label: "IP", minWidth: 110, prop: "ip",showOverflowTooltip:true,sortable: "custom"},
    { label: "加入时间", minWidth: 130, prop: "created_at",sortable: "custom"},
    { label: "最后修改时间", minWidth: 130, prop: "updated_at",sortable: "custom"},
  ]);

  const searchCondList =  ref([])

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  const getSalemanList = async function (page=1,limit=1000) {
    const {data} = await getSalesList({page,limit}); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    salesman_arr.value = data?.data;
    if(data?.me?.site_group !=-2||data?.me?.site_group !=-3){//非组长和业务员时，应该可以看到组列表
      const dept = data?.data.filter(x=>x.dept?.parent_id==4).map(x=>x.dept);
      teamList.value =[...new Map(dept.map(item => [item?.id, item])).values()];//去重
    }
  }

  function onCustomerOrder(row){
    delete row.items;
    delete row.logs;
    customerIndex(row,"post").then(res=> {
      if(res.code===0){
        row.isModified = false;
        ElMessage({message: `修改成功`,type: "success"})
        onSearch();
      }else{
        message(`失败，原因：${res.message}`, { type: "error"});
      }
    })
  }

  async function onSearch() {
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    loading.value = true;

    form.init_spent = '0';//大于0为历史客户
    form.total_spent = '0.01';//top排名的，必须要成单的
    if(form.tab_id==0){//全部
      form.customer_type = '0';
    }else if(form.tab_id==1){//老格式
      form.init_spent = '0.01';
      form.customer_type = '2';
    }else if(form.tab_id==2){//私域排名
      form.customer_type = '2';
    }else if(form.tab_id==3){//独立站排名
      form.customer_type = '1';
    }

    // if(form.hasOwnProperty('order_status')&&form.order_status>0)delete form.abnormal_label
    const { data } = await customerIndex(form); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    // columns.value = columns.value.filter(x=>data.db_fields.includes(x.label));
    // columnsKey.value = Date.now();
    dataField.value = data.db_fields;
    db_fields_all.value = data.db_fields_all;

    dataList.value = data.data;
    shopList.value = data.shop_list;
    searchCondList.value = data?.search_cond_arr;
    financial_status_arr.value = data?.financial_status_arr;
    shop_group_list_arr.value = data?.shop_group_list;
    template_url.value = data.template_url;


    selectValue.value = data.selectValue;
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.current_page;


    setTimeout(() => {
      loading.value = false;
    }, 500);

  }

//导入数据
  function importData() {
    addDrawer({
      size: "65%",
      title: "导入客户",
      contentRenderer: () => forms,
      props: {
        formInline: {
          template_url: template_url.value,
          dataList:[[]],
          // export_field:export_field,
          // id:row.id,
          checkCond:[salesman_arr.value]
        }
      },
      closeOnClickModal: false,
      sureBtnLoading: true,
      beforeSure: (done, { options, index,closeLoading }) => {
        const { formInline } = options.props as FormProps;
        if(formInline.dataList.length == 0){
          message(`你没有导入数据`, { type: "error" });
          closeLoading();
        }else if(formInline.dataList.filter(x=>x["状态检查"]!="数据检查正常").length > 0){
          const errorNum = formInline.dataList.filter(x=>x["状态检查"]!="数据检查正常").length;
          message(`您导入的数据有${errorNum}条文件格式错误，请改正后重新上传`, { type: "error" });
          closeLoading();
        }else{
          importCustomerList({list:formInline.dataList},"post").then(res=>{
            if(res.code==0){
              onSearch()
              if(res.data.filter(x=>x.i_status!='ok').length==0){//全部成功的关闭
                done();
                message(`已成功导入${res.data.filter(x=>x.i_status=='ok').length}条`, {
                  type: "success"
                });
              }else{
                formInline.dataList = formInline.dataList.map((da,idx) => ({
                  ...da,
                  '状态检查': res.data[idx]?.i_status||''
                }));
                message(`已成功导入${res.data.filter(x=>x.i_status=='ok').length}条,失败${res.data.filter(x=>x.i_status!='ok').length}条`, {
                  type: "warning"
                });
              }
            }else{
              formInline.dataList = []
              message(`导入失败,失败原因：`+res.message, {
                type: "error"
              });
            }
            closeLoading();
          })
        }
        // done(); // 需要关闭把注释解开即可
      },
    });
  }

  function  setBatchSearch(){
    // 兼容 Windows (\r\n) 和 Linux (\n)
    const lineBreak = navigator.platform.includes('Win') ? '\r\n' : '\n';
    // 将指定分隔符（如逗号）转换为换行符，并清理多余空格
    form.search = form.search.replace(/[,;]\s*/g, lineBreak).trim();

    addDialog({
      width: "30%",
      title: "设置批量查询",
      contentRenderer: ({ index }) => (
        <el-form size="small">
          <el-form-item label="查询条件">
            <el-radio-group v-model={form.search_field}>
              {searchCondList.value.map(item => (
                <el-radio value={item.value} disabled={item.value==''}>按{item.name}</el-radio>
              ))}
            </el-radio-group>
          </el-form-item>
          <el-form-item label="查询内容">
            <el-input
              v-model={form.search}
              rows="10"
              type="textarea"
              placeholder="多个回车换行"
            />
          </el-form-item>
        </el-form>
      ),
      closeCallBack: ({ options, args }) => {
        form.search = form.search.split(/\r?\n/).filter(Boolean).join(';');
      }
    });

  }
  function  openDialog(){}


  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  onMounted(async() => {
    onSearch();
    getSalemanList();
  });

  //导出功能
  const export_data = async () => {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const { data } = await customerIndex(toRaw({...form,page:1,export:1,limit:10000,'platformOrderId':getKeyList(curSelected, "platformOrderId").join(',')}),'get');
    const res = data.field
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, `客户列表${new Date().toISOString()}.xlsx`);
  }

  function seeCustomerDetail(e){
    let customerId = e.target.getAttribute('data-id')
    addDrawer({
      size: '60%',
      title: `客户详情:${customerId}`,
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      hideFooter: true,
      headerStyle:`{ marginBottom: '0px' }`,
      contentRenderer: () =>
        createVNode(customerDetailForm, {
          formInline: customerId
        }),
    });
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }




  const sortChange = (k: any) => {
    form.sortField = k.prop
    form.order = k.order=='descending'?'desc':'asc'
    onSearch()
  }


  function addVisitLog(id){
    function saveVisitLog(options,index){
      const FormRef = formRef.value.getRef();
      const curData = options.props.formInline;
      curData.customer_id = id;
      FormRef.validate(valid => {
        if (valid) {
          customerLogs(curData, "post").then(res => {
            if (res.code === 0) {
              message(`您已成功提交的这条回访数据`, { type: "success" });
              closeDialog(options, index);
              onSearch()
            } else {
              message(`回访失败，原因：${res.message}`, {type: "error"});
            }
          })
        }
      });
    }
    addDialog({
      title: `新增回访记录`,
      props: {
        formInline: JSON.parse(JSON.stringify( {})),//type1编辑，2浏览
      },
      width: "40%",
      draggable: true,
      hideFooter:false,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(visitForm, {ref: formRef, formInline: null}),
      footerButtons: [
        { label: "取消",size: "small",type: "info", btnClick: ({ dialog: { options, index }, button }) => {closeDialog(options, index);}},

        {label: "提交",size: "small",type: "success",
          btnClick: ({ dialog: { options, index }, button }) => {
            saveVisitLog(options,index)
          }
        }
      ],
    });
  }
  //批量保存所有的修改的订单
  function onSaveCrmBatch(){
    dataList.value.filter(x=>x.isModified==true).map(x=>onCustomerOrder(x));
  }
  const copy_customer = async (field='order_number') => {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const success = copyTextToClipboard(getKeyList(curSelected, field).join("\r\n"));
    success
      ? message("复制成功", { type: "success" })
      : message("复制失败", { type: "error" });
  }

  return {
    form,loading,columnsKey,sortChange,onSaveCrmBatch,copy_customer,
    columns,dataList,financial_status_arr,
    shopList,sta_order_statc,selectValue,salesman_arr ,shop_group_list_arr,
    export_data,db_fields_all,importData,
    onSearch,activeStatus,selectedNum,onSelectionCancel,
    resetForm, openDialog, pagination,
    handleSelectionChange,searchCondList,setBatchSearch,
    handleSizeChange, handleCurrentChange
  };
}
